package teacher;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;

@WebServlet("/TeacherDashboardDataServlet")
public class TeacherDashboardDataServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Integer teacherId = (Integer) session.getAttribute("teacher_id");

        if (teacherId == null) {
            response.sendRedirect("teacher_student.jsp");
            return;
        }

        try {
            Connectmysql conn = new Connectmysql(
                    "jdbc:mysql://localhost:3306/exam",
                    "root",
                    "root",
                    "com.mysql.cj.jdbc.Driver"
            );

            if (conn.open()) {
                StringBuilder json = new StringBuilder("{");

                // 任教课程数
                String courseSql = "SELECT COUNT(DISTINCT course_id) AS course_count FROM teaching WHERE teacher_id = ? AND status = 1";
                ResultSet rs = conn.executeSql(courseSql, new Object[]{teacherId});
                if (rs.next()) {
                    json.append("\"courseCount\":").append(rs.getInt("course_count")).append(",");
                }

                // 考试申请数
                String examSql = "SELECT COUNT(*) AS exam_count FROM exam WHERE teacher_id = ?";
                rs = conn.executeSql(examSql, new Object[]{teacherId});
                if (rs.next()) {
                    json.append("\"examCount\":").append(rs.getInt("exam_count")).append(",");
                }

                // 学生总数
                String studentSql = "SELECT COUNT(DISTINCT s.student_id) AS student_count " +
                        "FROM student s " +
                        "JOIN teaching t ON s.class_id = t.class_id " +
                        "WHERE t.teacher_id = ? AND t.status = 1";
                rs = conn.executeSql(studentSql, new Object[]{teacherId});
                if (rs.next()) {
                    json.append("\"studentCount\":").append(rs.getInt("student_count")).append(",");
                }

                // 待批改试卷数
                String pendingSql = "SELECT COUNT(*) AS pending_count FROM student_score " +
                        "WHERE exam_id IN (SELECT exam_id FROM exam WHERE teacher_id = ?) " +
                        "AND score IS NULL";
                rs = conn.executeSql(pendingSql, new Object[]{teacherId});
                if (rs.next()) {
                    json.append("\"pendingCount\":").append(rs.getInt("pending_count")).append(",");
                }

                // 近期考试（最近5个）
                json.append("\"recentExams\":[");
                String recentExamSql = "SELECT e.exam_id, e.exam_name, c.course_name, e.apply_time, e.status " +
                        "FROM exam e " +
                        "JOIN course c ON e.course_id = c.course_id " +
                        "WHERE e.teacher_id = ? " +
                        "ORDER BY e.apply_time DESC LIMIT 5";
                rs = conn.executeSql(recentExamSql, new Object[]{teacherId});
                boolean firstExam = true;
                while (rs.next()) {
                    if (!firstExam) {
                        json.append(",");
                    }
                    firstExam = false;

                    json.append("{");
                    json.append("\"exam_id\":");
                    json.append(rs.getInt("exam_id"));
                    json.append(",");

                    json.append("\"exam_name\":\"");
                    json.append(escapeJson(rs.getString("exam_name")));
                    json.append("\",");

                    json.append("\"course_name\":\"");
                    json.append(escapeJson(rs.getString("course_name")));
                    json.append("\",");

                    json.append("\"apply_time\":\"");
                    json.append(escapeJson(rs.getTimestamp("apply_time").toString()));
                    json.append("\",");

                    json.append("\"status\":");
                    json.append(rs.getInt("status"));
                    json.append(",");

                    json.append("\"status_text\":\"");
                    json.append(escapeJson(getStatusText(rs.getInt("status"))));
                    json.append("\"");

                    json.append("}");
                }
                json.append("],");

                // 任教课程
                json.append("\"teachingCourses\":[");
                String teachingSql = "SELECT DISTINCT c.course_name, cl.class_name " +
                        "FROM teaching t " +
                        "JOIN course c ON t.course_id = c.course_id " +
                        "JOIN class cl ON t.class_id = cl.class_id " +
                        "WHERE t.teacher_id = ? AND t.status = 1";
                rs = conn.executeSql(teachingSql, new Object[]{teacherId});
                boolean firstCourse = true;
                while (rs.next()) {
                    if (!firstCourse) {
                        json.append(",");
                    }
                    firstCourse = false;
                    json.append("{")
                            .append("\"course_name\":\"").append(escapeJson(rs.getString("course_name"))).append("\",")
                            .append("\"class_name\":\"").append(escapeJson(rs.getString("class_name"))).append("\"")
                            .append("}");
                }
                json.append("]");

                json.append("}");

                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(json.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "仪表盘数据加载失败");
        }
    }

    private String getStatusText(int status) {
        switch (status) {
            case 0: return "申请中";
            case 1: return "已批准";
            case 2: return "已激活";
            case 3: return "已结束";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }

    private String escapeJson(String input) {
        if (input == null) return "";
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}